import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { IOrgTreeUpdateMt, OrgTreeModel } from './translator'
import { updateUserInOrgTree } from './utils'
import { Subject } from 'rxjs'
type StateStore = {
	tree: OrgTreeModel[]
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	toggleTree: (item: OrgTreeModel) => void
	/**
	 *  更新终端导致的树变化
	 */
	updateMts: (updateMts: IOrgTreeUpdateMt[]) => void
}
const initialState: StateStore = {
	tree: [],
}
export const orgTreeRx = {
	reload$: new Subject(),
	addMt$: new Subject(),
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		toggleTree: (item) => {
			const tree = get().tree
			item.status.isOpen = !item.status.isOpen
			set({ tree: [...tree] })
		},
		updateMts: (updateMts) => {
			let prevTree = get().tree
			let tree = prevTree
			if (updateMts.length > 0) {
				tree = updateUserInOrgTree(prevTree, updateMts)
			}
			set({
				tree: [...tree],
			})
		},
	}))
)
export const useOrgTreeStore = create(store)
